package jwt.lab02;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.util.Properties;

public class ForwardLastMessage {

	public static void main(String[] args) throws MessagingException, IOException {
		Properties props = Utils.loadProperties(Utils.PROPERTIES_FILE);

		Message lastMsg = ReplyLastMessage.getLastMessage();
		System.out.println("Last message: " + Utils.messageToString(lastMsg));
		if (lastMsg.getAllRecipients() == null || lastMsg.getAllRecipients().length == 0) {
			System.out.println("Last message doesn't have reciepients...");
			return;
		}
		if (lastMsg.getFrom() == null || lastMsg.getFrom().length == 0) {
			System.out.println("Last message doesn't have from adresses");
			return;
		}

		Session session = Session.getDefaultInstance(props, null);

		Message forward = new MimeMessage(session);
		forward.setSubject("Fwd: " + lastMsg.getSubject());
		forward.setFrom(new InternetAddress(props.getProperty("mail.smtp.from")));
		forward.addRecipient(Message.RecipientType.TO, new InternetAddress(props.getProperty("mail.to")));
		
		BodyPart messageBodyPart = new MimeBodyPart();
		messageBodyPart.setText("Oto oryginalna wiadomość:\n\n");

		Multipart multipart = new MimeMultipart();
		multipart.addBodyPart(messageBodyPart);

		messageBodyPart = new MimeBodyPart();
		messageBodyPart.setDataHandler(lastMsg.getDataHandler());

		multipart.addBodyPart(messageBodyPart);

		forward.setContent(multipart);

		System.out.println("Sending message...");

		Transport transport = session.getTransport();
		transport.connect(props.getProperty("mail.smtp.user"), props.getProperty("mail.smtp.password"));
		transport.sendMessage(forward, forward.getAllRecipients());
		transport.close();

		System.out.println("[ OK ]");
	}
}
